package net.begincode.servlet.user;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.begincode.bean.BcUser;
import net.begincode.servlet.common.BaseServlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import utils.BQStringUtil;
import utils.FileUtil;
import utils.ImageCutUtil;
import utils.PropertiesUtil;

import com.google.gson.Gson;

public class UserServlet extends BaseServlet{
    
	private static final Log LOG = LogFactory.getLog(UserServlet.class);
	
	/**
	 * Ajax方式检测用户昵称或Email是否已存在
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void checkEAndNAjax(HttpServletRequest request, HttpServletResponse response) throws IOException{
	    checkEAndN(request, response);
	}
	/**
	 * 检查email和昵称是否存在
	 * @throws IOException 
	 * */
	public void checkEAndN(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String email = request.getParameter("email");
		String nickName = request.getParameter("nickname");
		List<BcUser> bcUsers = this.bcUserService.checkEmailAndNickName(email, nickName);
		Map<String,String> checkMap = new HashMap<String,String>();
		//默认都为yes，标识没有相同的
		checkMap.put("email", "yes");
		checkMap.put("nickName", "yes");
		Gson gson = new Gson();
		//循环，如果有相同的设置为no
		for(BcUser bcUser : bcUsers){
			if(email.equals(bcUser.getEmail())){
				checkMap.put("email", "no");
			}
			if(nickName.equals(bcUser.getNickname())){
				checkMap.put("nickName", "no");
			}
		}
		response.getWriter().print(gson.toJson(checkMap));
	}
	
	/**
	 * 获取用户登录信息
	 * */
	public void getUser(HttpServletRequest request, HttpServletResponse response){
		Gson gson = new Gson();
		try {
			Map<String, String> userMap  = this.getCookieInfo(request, response);
			response.getWriter().print(gson.toJson(userMap));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 注册用户
	 * @throws IOException 
	 * */
	public void addUser(HttpServletRequest request, HttpServletResponse response) throws IOException{
		Map<String, String> msgMap = new HashMap<String, String>();
		Gson gson = new Gson();
		String email = request.getParameter("email");
		String nickname = request.getParameter("nickname");
		String pwd = request.getParameter("pwd");
		String sex = request.getParameter("sex");
		if(email.equals("") || nickname.equals("") || pwd.equals("") || sex.equals("")){
			msgMap.put("msg", "fail");
		}else{
			BcUser bcUser = new BcUser();
			bcUser.setEmail(email);
			bcUser.setNickname(nickname);
			bcUser.setPwd(BQStringUtil.makeMD5(pwd));
			bcUser.setSex(sex);
			if(sex.equals("1")){
				bcUser.setPic("boy.jpg");
			}else{
				bcUser.setPic("show.jpg");
			}
			bcUser.setCdate(new Date());
			bcUser.setCheck_flag("0");
			bcUser.setAccount_power(BaseServlet.INIT_POWER);
			bcUser.setHashPwd(pwd);
			bcUser.setBeginid(UUID.randomUUID().toString());
			int returnValue = this.bcUserService.addBcUser(bcUser);
			bcUser.setBc_user_id(returnValue);
			if(returnValue > 0){
				//注册成功保存cookie
				this.addUserCookie(bcUser,"0", response);
				this.classifyService.addDefaultClassify(bcUser.getBc_user_id());
				msgMap.put("msg", "success");
			}else{
				msgMap.put("msg", "fail");
			}
		}
		
		response.getWriter().print(gson.toJson(msgMap));
	}
    
 
    
	
	public void updPassword(HttpServletRequest request, HttpServletResponse response){
        try {
        	 //获取用户表单数据
        	 String oldpwd = request.getParameter("oldpwd");
             String newpwd = request.getParameter("newpwd");
             //获取登录人信息
             Map<String, Object> msgMap = new HashMap<String, Object>();
             Gson gson = new Gson();
             Map<String, String> userInfo = this.getCookieInfo(request, response);
             BcUser bcUser = this.bcUserService.selUserByBeginId(userInfo.get("beginid"));
            
            if(!bcUser.getPwd().equals(BQStringUtil.makeMD5(oldpwd))){
                 msgMap.put("msg", "原密码不正确");
                
            }else{
                 bcUser.setPwd(BQStringUtil.makeMD5(newpwd));
                 int returnValue = this.bcUserService.updBcUser(bcUser);
                 if(returnValue > 0){
                     msgMap.put("msg", "密码修改成功");
                  }else{
                      msgMap.put("msg", "密码修改失败");
                  }
             }
             response.getWriter().print(gson.toJson(msgMap));
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getStackTrace());
        } catch (IOException e) {
            LOG.error(e.getStackTrace());
        }
	}
	


	

    /**
     * 查询密码，修改密码时使用
     * @param request
     * @param response
     */
    public void selPassword(HttpServletRequest request, HttpServletResponse response){
        try {
            String tempPath = PropertiesUtil.getTempPath();
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();  
            // threshold 极限、临界值，即硬盘缓存 1M  
            diskFactory.setSizeThreshold(1024 * 1024);  
            // repository 贮藏室，即临时文件目录  
            diskFactory.setRepository(new File(tempPath));  
          
            ServletFileUpload upload = new ServletFileUpload(diskFactory);  
            // 设置允许上传的最大文件大小 4M  
            upload.setSizeMax(4 * 1024 * 1024);  
            // 解析HTTP请求消息头  
            List fileItems = upload.parseRequest(request);  
            Iterator iter = fileItems.iterator();  
            while(iter.hasNext())  
            {  
                FileItem item = (FileItem)iter.next();  
                if(item.isFormField())  
                {  
                    System.out.println("处理表单内容 ...");  
                }else{  
                    
                    String fileName = "myicon.jpg";
                    long fileSize = item.getSize();  
                    File uploadFile = new File(tempPath + File.separator + fileName);  
                    item.write(uploadFile);  
                    System.out.println("处理上传的文件 文件大小" + fileSize);  
                }  
            }
            
            Gson gson = new Gson();
            Map<String, Object> msgMap = new HashMap<String, Object>();
            msgMap.put("msg", "success");
            response.getWriter().print(gson.toJson(msgMap));
        } catch (Exception e) {
            LOG.error(e.getStackTrace());
        }
    }
    
    
    
	/**
     * 查询用户信息
     * @param request
     * @param response
     */
    public void selUser(HttpServletRequest request, HttpServletResponse response){
        try {
            Gson gson = new Gson();
            Map<String, String> userInfo = this.getCookieInfo(request, response);
            String beginid = userInfo.get("beginid");
            BcUser bcUser = this.bcUserService.selUserByBeginId(beginid);
            //防止密码暴露
            bcUser.setPwd(null);
            Map<String, Object> msgMap = new HashMap<String, Object>();
            if((!"".equals(beginid) && beginid != null) || beginid.equals(bcUser.getBeginid())){
                msgMap.put("msg", "success");
                msgMap.put("bcUser", bcUser);
            }else{
                msgMap.put("msg", "fail");
            }
            response.getWriter().print(gson.toJson(msgMap));
        } catch (UnsupportedEncodingException e) {
            LOG.error(e.getStackTrace());
        } catch (IOException e) {
            LOG.error(e.getStackTrace());
        }
    }    
	
    /**
     * 跳转至修改头像页面
     * @param request
     * @param response
     * @throws IOException 
     * @throws ServletException 
     */
    public void updateIcon(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.getRequestDispatcher("/WEB-INF/page/uploadIcon.jsp").forward(request, response);;
    }
    
    /**
     * 截图方法
     * http://localhost:8080/begincode/user/cutImage?iconName=test.jpg&x1=74&y1=108&w=299&h=168
     * @param request
     * @param response
     */
    public void cutImage(HttpServletRequest request, HttpServletResponse response){
        int x = Integer.valueOf(request.getParameter("x1"));
        int y = Integer.valueOf(request.getParameter("y1"));
        int w = Integer.valueOf(request.getParameter("w"));
        int h = Integer.valueOf(request.getParameter("h"));
        String iconName = request.getParameter("iconName");
        String formatName = iconName.substring(iconName.lastIndexOf(".")+1);
        String tempPath = PropertiesUtil.getTempPath();
        String savePath = PropertiesUtil.getSavePath();
        try {
            ImageCutUtil.cutImage(x, y, w, h, formatName, iconName, tempPath, savePath);
            Gson gson = new Gson();
            Map<String, String> userInfo = this.getCookieInfo(request, response);
            String beginid = userInfo.get("beginid");
            BcUser bcUser = this.bcUserService.selUserByBeginId(beginid);
            bcUser.setPic(iconName);
            int returnValue = this.bcUserService.updBcUser(bcUser);
            Map<String, String> msgMap = new HashMap<String, String>();
            if(returnValue > 0){
                msgMap.put("msg", "success");
             }else{
                 msgMap.put("msg", "fail");
             }
            System.out.println(returnValue+"###"+msgMap);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(gson.toJson(msgMap));
        } catch (UnsupportedEncodingException e) {
        	e.printStackTrace();
            LOG.error(e.getStackTrace());
        } catch (IOException e) {
        	e.printStackTrace();
            LOG.error(e.getStackTrace());
        }
    }
	
    /**
     * 上传文件
     * @param request
     * @param response
     */
    public void uploadImage(HttpServletRequest request, HttpServletResponse response){
    	System.out.println("上传");
        try {
            String tempPath = PropertiesUtil.getTempPath();
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();  
            // threshold 极限、临界值，即硬盘缓存 1M  
            diskFactory.setSizeThreshold(1024 * 1024);  
            // repository 贮藏室，即临时文件目录  
            diskFactory.setRepository(new File(tempPath));  
            ServletFileUpload upload = new ServletFileUpload(diskFactory);  
            // 设置允许上传的最大文件大小 4M  
            upload.setSizeMax(4 * 1024 * 1024);  
            // 解析HTTP请求消息头  
            List fileItems = upload.parseRequest(request);  
            Iterator iter = fileItems.iterator();  
            String fileName = "";
            long fileSize = 0;
            String url = "";
            Gson gson = new Gson();
            Map<String, Object> msgMap = new HashMap<String, Object>();
            while(iter.hasNext())  
            {  
                FileItem item = (FileItem)iter.next();  
                if(item.isFormField())  
                {  
                    System.out.println("处理表单内容 ...");  
                }else{  
                    String formatName = item.getName().substring( item.getName().lastIndexOf(".")+1);
                    Map<String, String> userInfo = this.getCookieInfo(request, response);
                    //按照用户id为临时文件起名
                    fileName = "myIcon_" + userInfo.get("bcUserId")+"." + formatName;
                    fileSize = item.getSize();  
                    ImageCutUtil.compressImage(item.getInputStream(),new FileOutputStream(new File(tempPath + File.separator + fileName)), formatName);
                    System.out.println("处理上传的文件 文件大小" + fileSize);  
                }  
            }
            url = PropertiesUtil.getDomainName() + fileName;
            String[] files = {"{name: \""+fileName+"\",url: \""+url+"\",size: \""+fileSize+"\"}"};
            msgMap.put("files", files);
            msgMap.put("msg", "success");
            msgMap.put("pngUrl", url);
            response.getWriter().print(gson.toJson(msgMap));
        } catch (Exception e) {
        	e.printStackTrace();
            LOG.error(e.getStackTrace());
        }
    }
    

    
    /**
     * 修改用户信息
     * @param request
     * @param response
     */
    public void updUser(HttpServletRequest request, HttpServletResponse response){
            try {
                String nickname = request.getParameter("nickname");
//                String tel_phone = request.getParameter("tel_phone");
//                String receive_email = request.getParameter("receive_email");
                String email = request.getParameter("email");
                String sex = request.getParameter("sex");
                int bc_user_id = Integer.valueOf(request.getParameter("bc_user_id"));
                BcUser bcUser = new BcUser();
                bcUser.setBc_user_id(bc_user_id);
                bcUser.setNickname(nickname);
                bcUser.setSex(sex);
                bcUser.setEmail(email);
//                bcUser.setTel_phone(tel_phone);
                bcUser.setCheck_flag("1");
                int returnValue = this.bcUserService.updBcUser(bcUser);
               
                Gson gson = new Gson();
                Map<String, String> msgMap = new HashMap<String, String>();
                if(returnValue > 0){
                    //注册成功保存cookie
                    this.addUserCookie(this.bcUserService.selUserById(bc_user_id),"0", response);
                    msgMap.put("msg", "修改成功");
                }else{
                    msgMap.put("msg", "修改失败");
                }
                response.getWriter().print(gson.toJson(msgMap));
            } catch (UnsupportedEncodingException e) {
                LOG.error(e.getStackTrace());
            } catch (IOException e) {
                LOG.error(e.getStackTrace());
            }
    }
    /**
     * 查询User for spacemanager
     * */
    public void updUserForSapce(HttpServletRequest request, HttpServletResponse response) {
    	 try {
	    	Map<String, String> userInfo;
			userInfo = this.getCookieInfo(request, response);
	        String beginid = userInfo.get("beginid");
	        request.setAttribute("bcUser", this.bcUserService.selUserByBeginId(beginid));
			request.getRequestDispatcher("/WEB-INF/page/spaceManager.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    /**
     * 查询用户头像
     * @throws UnsupportedEncodingException 
     * */
    public void selUserIcon(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
    	String pic  = "";
    	String userId = request.getParameter("userId");
    	if(userId != null && !userId.equals("")){
       	 pic = this.bcUserService.selUserById(Integer.parseInt(userId)).getPic();
    	}else{
    		//没有userId，从cookie取
            Map<String, String> userInfo = this.getCookieInfo(request, response);
            String beginId = userInfo.get("beginid");
            pic = this.bcUserService.selUserByBeginId(beginId).getPic();
    	}
    	  Gson gson = new Gson();
    	  Map paMap = new HashMap();
    	  paMap.put("pic", pic);
    	  try {
    		  response.getWriter().print(gson.toJson(paMap));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }

}
